import React, { Component } from 'react'
import {NavLink} from 'react-router-dom'
// 导入store
import store, {actions} from '../store'

export default class Redux2 extends Component {
  constructor() {
    super();
    this.state = {
      age: 0,
      name: ''
    }
    this.input = React.createRef()
  }
  componentDidMount() {
    // setState方法需要的参数是一个对象
    // getState方法的返回值也是一个对象
    this.setState(store.getState());
    // 渲染页面时自动建立监听
    this.un = store.subscribe(()=>{
      // subscribe会在state变化时自动执行
      this.setState(store.getState());
    })
  }
  componentWillUnmount() {
    // 取消订阅
    this.un();
  }
  happyBirthday() {
    // 修改数据，通过dispatch触发action
    store.dispatch(actions.old());
  }
  birth() {
    store.dispatch(actions.birth());
    console.log(store.getState());
  }
  setName() {
    store.dispatch(actions.setName(this.input.current.value))
  }
  render() {
    // console.log(store.getState());
    return (
      <div>
        <p>redux的使用</p>
        <p>age:{this.state.age}</p>
        <p>name:{this.state.name}</p>
        <button onClick={()=>this.happyBirthday()}>过生日</button>
        <button onClick={()=>this.birth()}>出生</button>
        <input type="text" ref={this.input} />
        <button onClick={()=>this.setName()}>起名</button>
        <hr />
        <NavLink to="/redux">Redux</NavLink>
      </div>
    )
  }
}
